<template>
  <div class="chat-container">
    <!-- 聊天列表侧边栏 -->
    <div class="chat-sidebar">
      <div class="search-box">
        <el-input placeholder="搜索聊天..." v-model="searchKeyword"></el-input>
      </div>
      <div class="chat-list">
        <div
            v-for="user in chatUsers"
            :key="user.id"
            :class="['chat-user-item', { 'active': currentChatUserPhone === user.phoneNumber }]"
            @click="switchChatUser(user.phoneNumber)"
        >
          <el-avatar :size="40" :src="getUrl(user.imgUrl)"></el-avatar>
          <div class="user-info">
            <div class="user-name">{{ user.name }}</div>
            <div class="last-message">{{ user.lastMessage || '点击开始聊天' }}</div>
          </div>
          <div v-if="user.unreadCount > 0" class="unread-count">
            {{ user.unreadCount }}
          </div>
        </div>
      </div>
    </div>

    <!-- 聊天内容区域 -->
    <div class="chat-content" v-if="currentChatUserPhone">
      <div class="chat-header">
        <el-avatar :size="36" :src="getUrl(currentChatUser?.imgUrl)"></el-avatar>
        <div class="chat-user-name">{{ currentChatUser?.name || '选择聊天对象' }}</div>
      </div>

      <div class="message-list">
        <div
            v-for="(msg, index) in messages"
            :key="index"
            :class="['message-item', { 'sent': msg.isSent, 'received': !msg.isSent }]"
        >
          <div class="message-content">{{ msg.content }}</div>
          <div class="message-time">{{ formatTime(msg.sendTime) }}</div>
        </div>
      </div>

      <div class="message-input">
        <el-input
            v-model="inputMessage"
            placeholder="输入消息..."
            @keyup.enter.native="sendMessage"
            class="input-field"
        ></el-input>
        <el-button type="primary" @click="sendMessage">发送</el-button>
      </div>
    </div>

    <div class="no-selection" v-else>
      请选择一个聊天对象
    </div>
  </div>
</template>

<script>
import { getUrl } from '../utils/url.js'
import { useUserStore } from '../store/user.js'
import server from "../utils/request.js";
import {queryByDoctorId} from "../api/SysDoctorTeam.js";

export default {
  name: 'ChatPage',
  data() {
    return {
      // 当前登录用户
      currentUser: null,
      // 聊天用户列表
      chatUsers: [],
      // 当前正在聊天的用户ID
      currentChatUserId: null,
      //当前正在聊天的用户电话
      currentChatUserPhone: null,
      // 当前聊天用户信息
      currentChatUser: null,
      // 消息列表
      messages: [],
      // 输入的消息
      inputMessage: '',
      // 搜索关键词
      searchKeyword: '',
      // WebSocket连接
      websocket: null
    }
  },
  computed: {
    // 过滤后的聊天用户
    filteredChatUsers() {
      if (!this.searchKeyword) return this.chatUsers
      return this.chatUsers.filter(user =>
          user.username.toLowerCase().includes(this.searchKeyword.toLowerCase())
      )
    }
  },
  created() {
    // 获取当前登录用户信息
    this.currentUser = useUserStore().userInfo
    console.log(this.currentUser)

    // 初始化WebSocket连接
    this.initWebSocket()

    // 获取聊天用户列表(实际项目中应该从后端API获取)
    this.getChatUsers()
  },
  beforeDestroy() {
    // 关闭WebSocket连接
    if (this.websocket) {
      this.websocket.close()
    }
  },
  methods: {
    getUrl,

    // 初始化WebSocket连接
    initWebSocket() {
      if (!this.currentUser || !this.currentUser.phone) {
        console.error('用户信息不存在，无法初始化WebSocket')
        return
      }

      // WebSocket连接地址，注意协议：http对应ws，https对应wss
      const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
      const wsUrl = `${wsProtocol}//localhost:8080/ws/chat/${this.currentUser.phone}`
      this.websocket = new WebSocket(wsUrl)

      // 连接成功
      this.websocket.onopen = () => {
        console.log('WebSocket连接成功')
      }

      // 接收消息
      this.websocket.onmessage = (event) => {
        console.log('收到消息:', event.data)
        this.handleReceivedMessage(event.data)
      }

      // 连接关闭
      this.websocket.onclose = () => {
        console.log('WebSocket连接关闭')
        // 可以在这里实现重连逻辑
      }

      // 连接错误
      this.websocket.onerror = (error) => {
        console.error('WebSocket错误:', error)
      }
    },

    // 处理收到的消息
    handleReceivedMessage(message) {
      try {
        // 消息格式："发送者ID:消息内容"
        const [senderPhone, content] = message.split(':', 2)

        // 添加到消息列表
        if (this.currentChatUserPhone === senderPhone) {
          this.messages.push({
            content,
            sendTime: new Date(),
            isSent: false
          })

          // 标记消息为已读
          this.markAsRead(senderPhone, this.currentUser.phone)
        } else {
          // 如果不是当前聊天窗口，更新未读计数
          this.updateUnreadCount(senderPhone)
        }

        // 滚动到底部
        this.scrollToBottom()
      } catch (e) {
        console.error('解析消息失败:', e)
      }
    },

    // 获取聊天用户列表
    async getChatUsers() {
      let {data:data} = await queryByDoctorId(this.currentUser.id)
      console.log(data)
      this.chatUsers = data.data;
    },

    // 切换聊天用户
    switchChatUser(phone) {
      this.currentChatUserPhone = phone
      this.currentChatUser = this.chatUsers.find(user => user.phoneNumber === phone)
      console.log(this.currentChatUser)

      // 清除未读计数
      this.clearUnreadCount(phone)

      // 获取聊天历史记录
      this.getChatHistory(this.currentUser.phone, phone)
    },

    // 获取聊天历史记录
    getChatHistory(senderPhone, receiverPhone) {
      server.get('/chat/history', {
        params: {
          senderPhone,
          receiverPhone
        }
      }).then(response => {
        this.messages = response.data.map(msg => ({
          content: msg.messageContent,
          sendTime: new Date(msg.sendTime),
          isSent: msg.senderPhone === this.currentUser.phone
        }))

        // 滚动到底部
        this.scrollToBottom()
      }).catch(error => {
        console.error('获取聊天历史失败:', error)
        this.messages = []
      })
    },

    // 发送消息
    sendMessage() {
      if (!this.inputMessage.trim() || !this.currentChatUserPhone) return

      // 构建消息格式："接收者ID:消息内容"
      const message = `${this.currentChatUserPhone}:${this.inputMessage.trim()}`

      if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
        // 发送消息
        this.websocket.send(message)

        // 添加到消息列表
        this.messages.push({
          content: this.inputMessage.trim(),
          sendTime: new Date(),
          isSent: true
        })

        // 更新最后一条消息
        this.updateLastMessage(this.currentChatUserPhone, this.inputMessage.trim())

        // 清空输入框
        this.inputMessage = ''

        // 滚动到底部
        this.scrollToBottom()
      } else {
        this.$message.error('连接未建立，请稍后重试')
      }
    },

    // 标记消息为已读
    markAsRead(senderPhone, receiverPhone) {
      server.post(`/chat/read/${senderPhone}/${receiverPhone}`).catch(error => {
        console.error('标记消息为已读失败:', error)
      })
    },

    // 更新未读计数
    updateUnreadCount(userPhone) {
      const user = this.chatUsers.find(u => u.phoneNumber === userPhone)
      if (user) {
        user.unreadCount = (user.unreadCount || 0) + 1
      }
    },

    // 清除未读计数
    clearUnreadCount(userPhone) {
      const user = this.chatUsers.find(u => u.phoneNumber === userPhone)
      if (user) {
        user.unreadCount = 0
      }
    },

    // 更新最后一条消息
    updateLastMessage(userPhone, message) {
      const user = this.chatUsers.find(u => u.phoneNumber === userPhone)
      if (user) {
        user.lastMessage = message
      }
    },

    // 格式化时间
    formatTime(date) {
      const d = new Date(date)
      return `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`
    },

    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const messageList = this.$el.querySelector('.message-list')
        if (messageList) {
          messageList.scrollTop = messageList.scrollHeight
        }
      })
    }
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 100%;
  width: 100%;
}

.chat-sidebar {
  width: 300px;
  border-right: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;
}

.search-box {
  padding: 10px;
  border-bottom: 1px solid #e6e6e6;
}

.chat-list {
  flex: 1;
  overflow-y: auto;
}

.chat-user-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.chat-user-item:hover {
  background-color: #f5f7fa;
}

.chat-user-item.active {
  background-color: #e6f7ff;
}

.user-info {
  margin-left: 10px;
  flex: 1;
  overflow: hidden;
}

.user-name {
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.last-message {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.unread-count {
  background-color: #ff4d4f;
  color: white;
  border-radius: 10px;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 10px 15px;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
}

.chat-user-name {
  margin-left: 10px;
  font-weight: 500;
}

.message-list {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.message-item {
  margin-bottom: 15px;
  max-width: 70%;
}

.message-item.sent {
  margin-left: auto;
}

.message-item.received {
  margin-right: auto;
}

.message-content {
  padding: 8px 12px;
  border-radius: 8px;
  word-wrap: break-word;
}

.message-item.sent .message-content {
  background-color: #409eff;
  color: white;
}

.message-item.received .message-content {
  background-color: white;
  border: 1px solid #e6e6e6;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  text-align: right;
}

.message-input {
  padding: 10px 15px;
  border-top: 1px solid #e6e6e6;
  display: flex;
  gap: 10px;
}

.input-field {
  flex: 1;
}

.no-selection {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}
</style>
